<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Brand extends BaseController {

    // 后台配置名称
    private $cameraZoomName = 'brand_camera_zoom';
    private $powerTimeName = 'brand_power_time';
    private $powerWeek = 'power_week';
    private $powerHoliday = 'power_holiday';
    private $signIntervalName = 'brand_sign_interval';
    private $brandPawName = 'brand_paw';
    private $gradePowerTimeName = 'grade_power_time';
    // 定时开关机v2
    private $powerTimeV2Name = 'brand_power_time_v2';

	public function __construct() {
        parent::__construct();
        // 后台初始化方法
        $this->admin_init();
        // 如果是超管，就跳转到超管的控制器
        if($this->userType != USER_TYPE_SCHOOL && $this->userType != USER_TYPE_TEACHER) redirect(admin_url("login"));
        // 加载库
        $this->load->model('classesModel');
        $this->load->model('configModel');
        $this->load->model('schoolModel');
    }

    // 班牌列表
    public function index() {
        // 连接socket
        $channelId = time();
        $dataSource = '_sae/channel/create_channel/'. $channelId;
        $channelData = file_get_contents(web_url($dataSource));
        $channelData = json_decode($channelData, true);
        if(strstr($channelData['data'], '120.25.177.161')) {
            // 非新浪云的socket，不用转换为wss
            $this->socketUrl = $channelData['data'];
        } else {
            $this->socketUrl = str_replace("ws:", "wss:", $channelData['data']);
        }

        $this->channelId = CHANNEL_ID_PREFIX. $channelId;
        // 获取班牌摄像头缩放尺寸
        $schoolZoomConfig = $this->configModel->get_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->cameraZoomName);
        $this->zoomConfig = $schoolZoomConfig ? $schoolZoomConfig['config_value'] : BRAND_CAMERA_ZOOM;
        // 获取班牌定时开关机时间
        $schoolPowerTime = $this->configModel->get_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->powerTimeName);
        $this->powertime = $schoolPowerTime ? $schoolPowerTime['config_value'] : "";
        // 获取班牌考勤时间
        $schoolSignIntervalConfig = $this->configModel->get_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->signIntervalName);
        $this->signIntervalConfig = $schoolSignIntervalConfig ? $schoolSignIntervalConfig['config_value'] : BRAND_SIGN_INTERVAL;
        // 获取班牌默认密码
        $schoolBrandPawConfig = $this->configModel->get_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->brandPawName);
        $this->defaultBrandPaw = $schoolBrandPawConfig ? $schoolBrandPawConfig['config_value'] : '123456';

        // 获取班级列表
        $params['schoolId'] = $this->rmxSchool['id'];
        $params['campusId'] = $this->campusInfo['id'];
        $params['isDelete'] = 0;
        $this->classList = $this->classesModel->get_class_list($params);

        // 生成又拍云签名,用于导入
        require_once('vendor/autoload.php');
        $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
        $serviceConfig->setFormApiKey(UP_FORM_API);
        $serviceConfig->getImageUploadParams(UP_FILEPATH, $this->policy, $this->signature);

        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "brand". DIRECTORY_SEPARATOR. "index");
    }
    // 获取学校班牌列表
    public function get_brand_list(){
        $classIdArr = array();
        if($this->get('gradeId')) {
            // 获取年级下的班级
            $classParams['gradeId'] = $this->get('gradeId');
            $classParams['isDelete'] = 0;
            $classArr = $this->classesModel->get_class_list($classParams);
            if($classArr) {
                foreach($classArr as $class) {
                    array_push($classIdArr, $class['id']);
                }
                $totalParams['classIdSet'] = $data['classIdSet'] = implode(',', $classIdArr);
            }
        }
        // 教师权限登录时，只获取任课班级的
        if($this->rmxUser['user_type'] == USER_TYPE_TEACHER) {
            if($classIdArr) {
                $teacherClassIdArr = array();
                foreach($this->rmxUser['classIdArr'] as $id) {
                    if(in_array($id, $classIdArr)) {
                        array_push($teacherClassIdArr, $id);
                    }
                    $teacherClassIdStr = implode(',', $teacherClassIdArr);
                }
                // 若筛选了年级，没有匹配内容，设置成-1
                $totalParams['classIdSet'] = $data['classIdSet'] = $teacherClassIdStr ? $teacherClassIdStr : '-1';
            } else {        
                $totalParams['classIdSet'] = $data['classIdSet'] = $this->rmxUser['class_ids'];
            }
        }

        // 获取数据条数
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        $totalParams['campusId'] = $this->campusInfo['id'];
        $totalParams['getRowNumber'] = true;
        $total = $this->classesModel->get_brand_list($totalParams);
        // 获取数据
        $data['pageStart'] = $this->get('start');
        $data['pageSize']= $this->get("length");
        $data['schoolId'] = $this->rmxSchool['id'];
        $data['campusId'] = $this->campusInfo['id'];
        // 按班级名称排序
        // $data['orderByClassNameAndState'] = 1;
        // 不按是否在线排序
        // $data['orderByClassName'] = 1;
        $brandList = $this->classesModel->get_brand_list($data);
        // 获取班牌默认密码
        $schoolBrandPawConfig = $this->configModel->get_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->brandPawName);
        $defaultBrandPaw = $schoolBrandPawConfig ? $schoolBrandPawConfig['config_value'] : '123456';
        // 获取班牌摄像头缩放尺寸
        $schoolZoomConfig = $this->configModel->get_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->cameraZoomName);
        $defaultZoom = $schoolZoomConfig ? $schoolZoomConfig['config_value'] : BRAND_CAMERA_ZOOM;
        // 获取班牌考勤时间
        $schoolSignIntervalConfig = $this->configModel->get_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->signIntervalName);
        $defaultInterval = $schoolSignIntervalConfig ? $schoolSignIntervalConfig['config_value'] : BRAND_SIGN_INTERVAL;
        foreach($brandList as &$brand) {
            $classInfo = $this->classesModel->get_class_info($brand['class_id']);
            $brand['className'] = $classInfo ? $classInfo['class_name'] : '';
            // 毕业班级
            if($classInfo['is_graduated'] == 1) {
                $brand['className'] = '';
                $brand['is_online'] = 0;
            }
            // 班级已删除
            if(empty($classInfo)) {
                $brand['is_online'] = 0;
            }
            $campusInfo = $this->schoolModel->get_campus_info($brand['campus_id']);
            $brand['campusName'] = $campusInfo['campus_name'];
            // 判断是否跟默认密码相同
            if($defaultBrandPaw == $brand['brand_password']) {
                $brand['isDefaultPaw'] = true;
            } else {
                $brand['isDefaultPaw'] = false;
            }
            // 判断是否跟默认缩放比例相同
            if($defaultZoom == $brand['brand_camera_zoom']) {
                $brand['isDefaultZoom'] = true;
            } else {
                $brand['isDefaultZoom'] = false;
            }
            // 判断是否跟默认考勤时间相同
            if($defaultInterval == $brand['sign_interval']) {
                $brand['isDefaultInterval'] = true;
            } else {
                $brand['isDefaultInterval'] = false;
            }
            if($brand['allow_send'] == 1) {
                $brand['allow_send_chinese'] = '允许发送文字内容';
            } else {
                $brand['allow_send_chinese'] = '关闭';
            }
            // 班牌类型
            $brand['typeName'] = transform_brand_type($brand['type']);
        }
        // 返回值
        exit(admin_table_data($total, $brandList));
    }
    // 保存班牌信息
    public function save_brand_action(){
        $brandId = $this->post("id");
        $password = $this->post("brand_password");
        $allowSend = $this->post("allow_send");
        // 判断教师权限
        $this->checkTeacherRoleByBrand($brandId);

        if(!$password) throw new Exception("请填写班牌管理密码");

        // 获取班牌信息
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if($brandInfo['school_id'] != $this->rmxSchool['id']) throw new Exception("参数错误，请刷新后重试");
        // 入库
        $data['brand_password'] = $password;
        $data['allow_send'] = $allowSend;
        $data['updatetime'] = date("Y-m-d H:i:s");
        $this->db->update(ClassesModel::$brandTable, $data,"id='{$brandId}'");

        exit(json("修改班牌信息成功", true));
    }

    // 发送屏幕截图请求
    public function screen_shot(){
        $brandId = $this->get("brand");
        $channelId = $this->get("channel");
        // 检查班牌状态
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo || !$brandInfo['is_online'] || $brandInfo['school_id'] != $this->rmxSchool['id']) throw new Exception("班牌已离线，发送截图请求失败");
        // 推送消息到客户端
        $this->load->library('socket');
        $this->socket->send_screen_shot_msg($brandId, $channelId);

        exit(json("发送远程截屏请求成功", true));
    }

    // 发送退出应用请求
    public function quit(){
        $brandId = $this->get("brand");
        $channelId = $this->get("channel");

        // 检查班牌状态
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo || !$brandInfo['is_online'] || $brandInfo['school_id'] != $this->rmxSchool['id']) throw new Exception("班牌已离线，发送退出请求失败");
        // 推送消息到客户端
        $this->load->library('socket');
        $this->socket->send_quit_msg($brandId, $channelId);

        // 插入日志
        $this->load->library('logger');
        $actionType = $this->logger->get_action_type('brand');
        $this->logger->save_log_action(array(
            'school_id' => $this->rmxSchool['id'],
            'campus_id' => $this->campusInfo['id'],
            'user_type' => $this->rmxUser['user_type'],
            'user_id' => $this->rmxUser['id'],
            'realname' => $this->rmxUser['realname'],
            'action_type' => $actionType,
            'content' =>'退出应用，班牌id：' . $brandInfo['id']
        ));

        exit(json("发送退出应用请求成功", true));
    }

    // 发送远程关机请求
    public function power_off(){
        $brandId = $this->get("brand");
        $channelId = $this->get("channel");

        // 检查班牌状态
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo || !$brandInfo['is_online'] || $brandInfo['school_id'] != $this->rmxSchool['id']) throw new Exception("班牌已离线，发送关机请求失败");
        // 推送消息到客户端
        $this->load->library('socket');
        $this->socket->send_power_off_msg($brandId, $channelId);

        // 插入日志
        $this->load->library('logger');
        $actionType = $this->logger->get_action_type('brand');
        $this->logger->save_log_action(array(
            'school_id' => $this->rmxSchool['id'],
            'campus_id' => $this->campusInfo['id'],
            'user_type' => $this->rmxUser['user_type'],
            'user_id' => $this->rmxUser['id'],
            'realname' => $this->rmxUser['realname'],
            'action_type' => $actionType,
            'content' =>'远程关机，班牌id：' . $brandInfo['id']
        ));

        exit(json("发送关机请求成功", true));
    }

    // 发送远程重启请求
    public function power_restart(){
        $brandId = $this->get("brand");
        $channelId = $this->get("channel");

        // 检查班牌状态
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo || !$brandInfo['is_online'] || $brandInfo['school_id'] != $this->rmxSchool['id']) throw new Exception("班牌已离线，发送重启请求失败");
        // 推送消息到客户端
        $this->load->library('socket');
        $this->socket->send_power_restart_msg($brandId, $channelId);

        // 插入日志
        $this->load->library('logger');
        $actionType = $this->logger->get_action_type('brand');
        $this->logger->save_log_action(array(
            'school_id' => $this->rmxSchool['id'],
            'campus_id' => $this->campusInfo['id'],
            'user_type' => $this->rmxUser['user_type'],
            'user_id' => $this->rmxUser['id'],
            'realname' => $this->rmxUser['realname'],
            'action_type' => $actionType,
            'content' =>'远程重启，班牌id：' . $brandInfo['id']
        ));

        exit(json("发送重启请求成功", true));
    }

    // 获取定时开关机时间
    public function get_power_time(){
        $brandId = $this->get("brand");
        // 检查班牌状态
        if($brandId == 0) {
            $schoolPowerTime = $this->configModel->get_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->powerTimeName);
            $powerTime = json_decode($schoolPowerTime['config_value'], true);
        } else {
            $brandInfo = $this->classesModel->get_brand_info($brandId);
            $powerTime = json_decode($brandInfo['power_time'], true);
        }

        exit(json("", true, $powerTime));
    }

    // 设置定时开关机时间
    public function save_power_time(){
        $this->load->library('socket');
        $brandId = $this->post("brand");
        // 判断教师权限
        $this->checkTeacherRoleByBrand($brandId);
        $powerTime = $this->post("time") ? $this->post("time") : array();
        $powerTimeJson = json_encode($powerTime);
        // 判断开机时间是否关机时间
        $arr = json_decode($powerTimeJson, true);
        $arrSort = array();
        foreach($arr as $time) {
            $startTime = $time['starttime'];
            $endTime = $time['endtime'];         
            $startTimeArr = explode(':', $startTime);
            $endTimeArr = explode(':', $endTime);
            if($startTimeArr[0] > $endTimeArr[0]){
                throw new Exception('开机时间不能大于关机时间');
            }
            if($startTimeArr[0] === $endTimeArr[0]){
                if($startTimeArr[1] === $endTimeArr[1]){
                    throw new Exception('开机时间不能等于关机时间');
                }
                if($startTimeArr[1] > $endTimeArr[1]){
                    throw new Exception('开机时间不能大于关机时间');
                }
            }
            // 按时间排序
            $arrSort[str_replace(':', '', $time['starttime'])] = array(
                'starttime' => $time['starttime'],
                'endtime' => $time['endtime']
            );
        }
        // 按时间排序
        ksort($arrSort);
        // 数组下标重0开始
        $arrSort = array_values($arrSort);
        // 判断开始时间是否大于上个结束时间
        foreach($arrSort as $key => $time) {
            // 从第二个开始判断
            if($key > 0) {
                $start = str_replace(':', '', $time['starttime']);
                $lastEnd = str_replace(':', '', $arrSort[$key - 1]['endtime']);
                if($start <= $lastEnd) {
                    throw new Exception('时间段不能重叠');
                }
            } 
        }
        $powerTimeJson = json_encode($arrSort, JSON_UNESCAPED_UNICODE);

        // 班牌开关机时间（新逻辑）
        $week = $this->configModel->get_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], 'power_week');
        $holiday = $this->configModel->get_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], 'power_holiday');
        if($week && isset($week['config_value'])) {
            $weekArr = explode(',', $week['config_value']);
            sort($weekArr);
        } else {
            // 如未设置，默认为整周
            $weekArr = array(1,2,3,4,5,6,7);
        }
        if($holiday && isset($holiday['config_value'])) {
            $holidayArr = json_decode($holiday['config_value'], true);
        } else {
            $holidayArr = array();
        }
        // 检查是否设置全校的班牌ID
        if($brandId == 0) {
            // 置全部班牌定时开关机时间
            $this->configModel->save_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->powerTimeName, $powerTimeJson);
            // 入库
            $saveData['power_time'] = $powerTimeJson;
            $this->db->update(ClassesModel::$brandTable, $saveData,"`school_id`='{$this->rmxSchool['id']}' AND `campus_id`='{$this->campusInfo['id']}'");

            // 清空年级定时开关机

            // 推送消息到客户端
            $params['schoolId'] = $this->rmxSchool['id'];
            $params['campusId'] = $this->campusInfo['id'];
            $params['online'] = 1;
            $brandList = $this->classesModel->get_brand_list($params);
            foreach($brandList as $brand) {
                $this->socket->send_power_time_msg($brand['id'], $powerTime, $weekArr, $holidayArr);
            }
        } else {
            // 入库
            $saveData['power_time'] = $powerTimeJson;
            $this->db->update(ClassesModel::$brandTable, $saveData,"id='{$brandId}'");
            // 检查班牌状态
            $brandInfo = $this->classesModel->get_brand_info($brandId);
            // 推送消息到客户端
            $this->socket->send_power_time_msg($brandId, $powerTime, $weekArr, $holidayArr);
        }

        exit(json("保存开关机时间成功", true));
    }

    // 设置定时开关机时间v2
    public function save_power_time_v2(){
        $this->load->library('socket');
        $week = $this->post('week');
        $brandId = $this->post("brand");
        if(empty($week)) {
            throw new Exception('系统错误');
        }
        if($brandId) {
            // 判断教师权限
            $this->checkTeacherRoleByBrand($brandId);
        }

        $powerTime = $this->post("time") ? $this->post("time") : array();
        $powerTimeJson = json_encode($powerTime);
        // 判断开机时间是否关机时间
        $arr = json_decode($powerTimeJson, true);
        $arrSort = array();
        foreach($arr as $time) {
            $startTime = $time['starttime'];
            $endTime = $time['endtime'];         
            $startTimeArr = explode(':', $startTime);
            $endTimeArr = explode(':', $endTime);
            if($startTimeArr[0] > $endTimeArr[0]){
                throw new Exception('开机时间不能大于关机时间');
            }
            if($startTimeArr[0] === $endTimeArr[0]){
                if($startTimeArr[1] === $endTimeArr[1]){
                    throw new Exception('开机时间不能等于关机时间');
                }
                if($startTimeArr[1] > $endTimeArr[1]){
                    throw new Exception('开机时间不能大于关机时间');
                }
            }
            // 按时间排序
            $arrSort[str_replace(':', '', $time['starttime'])] = array(
                'starttime' => $time['starttime'],
                'endtime' => $time['endtime']
            );
        }
        // 按时间排序
        ksort($arrSort);
        // 数组下标重0开始
        $arrSort = array_values($arrSort);
        // 判断开始时间是否大于上个结束时间
        foreach($arrSort as $key => $time) {
            // 从第二个开始判断
            if($key > 0) {
                $start = str_replace(':', '', $time['starttime']);
                $lastEnd = str_replace(':', '', $arrSort[$key - 1]['endtime']);
                if($start <= $lastEnd) {
                    throw new Exception('时间段不能重叠');
                }
            } 
        }
        $powerTimeArr = $arrSort;

        // 检查是否设置全校的班牌ID
        if($brandId == 0) {
            // 学校原来开关机配置
            $schoolPowerTimeV2 = $this->configModel->get_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->powerTimeV2Name);
            $schoolPowerTimeV2Arr = json_decode($schoolPowerTimeV2['config_value'], true);
        } else {
            // 该班牌的开关机
            $brandInfo = $this->classesModel->get_brand_info($brandId);
            $schoolPowerTimeV2Arr = json_decode($brandInfo['power_time_v2'], true);
        }
       
        $schoolPowerTimeV2Arr[$week] = $powerTimeArr;
        $schoolPowerTimeV2Json = json_encode($schoolPowerTimeV2Arr, JSON_UNESCAPED_UNICODE);
        // 计算定时开关机v2，返回给班牌
        $holiday = $this->configModel->get_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->powerHoliday);
        $powerTimeV2SocketData = $this->_get_power_time_v2($schoolPowerTimeV2Json, $holiday['config_value']);

        // var_export($powerTimeV2SocketData);exit;

        // 检查是否设置全校的班牌ID
        if($brandId == 0) {
            //  重置全部班牌定时开关机时间
            $this->configModel->save_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->powerTimeV2Name, $schoolPowerTimeV2Json);
            // 入库
            $saveData['power_time_v2'] = $schoolPowerTimeV2Json;
            $this->db->update(ClassesModel::$brandTable, $saveData,"`school_id`='{$this->rmxSchool['id']}' AND `campus_id`='{$this->campusInfo['id']}'");

            // 清空年级定时开关机
            $gradeParams['schoolId'] = $this->rmxSchool['id'];
            $gradeParams['campusId'] = $this->campusInfo['id'];
            $gradeParams['isDelete'] = 0;
            $gradeList = $this->classesModel->get_grade_list($gradeParams);
            foreach($gradeList as $grade) {
                $gradePowerTime= $this->configModel->get_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->gradePowerTimeName . '_' . $grade['id']);
                if($gradePowerTime) {
                    $this->configModel->save_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->gradePowerTimeName . '_' . $grade['id'], '');
                }
            }

            // 推送消息到客户端
            $params['schoolId'] = $this->rmxSchool['id'];
            $params['campusId'] = $this->campusInfo['id'];
            $params['online'] = 1;
            $brandList = $this->classesModel->get_brand_list($params);
            foreach($brandList as $brand) {
                $this->socket->send_power_time_v2_msg($brand['id'], $powerTimeV2SocketData);
            }
        } else {
            // 入库
            $saveData['power_time_v2'] = $schoolPowerTimeV2Json;
            $this->db->update(ClassesModel::$brandTable, $saveData, "id='{$brandId}'");
            // 检查班牌状态
            $brandInfo = $this->classesModel->get_brand_info($brandId);
            if($brandInfo['is_online'] == 1) {
                // 推送消息到客户端
                $this->socket->send_power_time_v2_msg($brandId, $powerTimeV2SocketData);
            }
        }

        // 插入日志
        $this->load->library('logger');
        $actionType = $this->logger->get_action_type('update');
        if($brandId == 0) {
            $content = '修改默认定时开关机时间';
        } else {
            $content = '修改班牌定时开关机时间，班牌id：' . $brandId;
        }
        $this->logger->save_log_action(array(
            'school_id' => $this->rmxSchool['id'],
            'campus_id' => $this->campusInfo['id'],
            'user_type' => $this->rmxUser['user_type'],
            'user_id' => $this->rmxUser['id'],
            'realname' => $this->rmxUser['realname'],
            'action_type' => $actionType,
            'content' => $content
        ));

        exit(json("保存成功", true));
    }

    // 重置默认开关机时间
    public function reset_power_time_v2() {
        $this->load->library('socket');
        // 学校默认开关机
        $schoolPowerTimeV2 = $this->configModel->get_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->powerTimeV2Name);
        $schoolPowerTimeV2Value = $schoolPowerTimeV2['config_value'];

        $brandId = $this->post('brand');
        $gradeId = $this->post('grade');
        $brandIdArr = $this->post('brand_arr');
        // var_export($brandIdArr);exit;
        // 计算定时开关机v2，返回给班牌
        $holiday = $this->configModel->get_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->powerHoliday);
        $powerTimeV2SocketData = $this->_get_power_time_v2($schoolPowerTimeV2Value, $holiday['config_value']);
        if($brandId) {
            // 单个班牌
            $saveData['power_time_v2'] = $schoolPowerTimeV2Value;
            $saveData['updatetime'] = date('Y-m-d H:i:s');
            $this->db->update(ClassesModel::$brandTable, $saveData, "id='{$brandId}'");
            // 检查班牌状态
            $brandInfo = $this->classesModel->get_brand_info($brandId);
            if($brandInfo['is_online'] == 1) {
                // 推送消息到客户端
                $this->socket->send_power_time_v2_msg($brandId, $powerTimeV2SocketData);
            }
        } elseif($gradeId) {
            // 年级班牌
            // 设置年级班牌定时开关机时间
            $this->configModel->save_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->gradePowerTimeName . '_' . $gradeId, '');
            // 入库
            $classArr = $this->classesModel->get_class_list_by_grade($gradeId);
            // 班级id集合
            $classIdArr = array();
            $updateBatch = array();
            foreach($classArr as $class) {
                $updateBatch[] = array(
                    'class_id' => $class['id'],
                    'power_time_v2' => $schoolPowerTimeV2Value,
                    'updatetime' => date('Y-m-d H:i:s')
                );
                array_push($classIdArr, $class['id']);
            }
            if($updateBatch) {
                $this->db->update_batch(ClassesModel::$brandTable, $updateBatch, 'class_id');
            }
            if($classIdArr) {
                // 推送消息到客户端
                $classIdSet = implode(',', $classIdArr);
                $params['schoolId'] = $this->rmxSchool['id'];
                $params['campusId'] = $this->campusInfo['id'];
                $params['online'] = 1;
                $params['classIdSet'] = $classIdSet;
                $brandList = $this->classesModel->get_brand_list($params);
                // echo '<pre>';var_export($brandList);exit;
                foreach($brandList as $brand) {
                    $this->socket->send_power_time_v2_msg($brand['id'], $powerTimeV2SocketData);
                }
            }
        } elseif($brandIdArr) {
            // 批量设置
            $updateBatch = array();
            foreach($brandIdArr as $brandId) {
                $updateBatch[] = array(
                    'id' => $brandId,
                    'power_time_v2' => $schoolPowerTimeV2Value,
                    'updatetime' => date('Y-m-d H:i:s')
                );
            }
            if($updateBatch) {
                $this->db->update_batch(ClassesModel::$brandTable, $updateBatch, 'id');
            }

            // 推送消息到客户端
            $params['schoolId'] = $this->rmxSchool['id'];
            $params['campusId'] = $this->campusInfo['id'];
            $params['online'] = 1;
            $brandList = $this->classesModel->get_brand_list($params);
            $brandList = array_value_to_key($brandList, 'id');
            // echo '<pre>';var_export($brandList);exit;
            foreach($brandIdArr as $brandId) {
                if(isset($brandList[$brandId])) {
                    $this->socket->send_power_time_v2_msg($brandId, $powerTimeV2SocketData);
                }
            }
        } else {
            throw new Exception('参数错误');
        }

        // 插入日志
        $this->load->library('logger');
        $actionType = $this->logger->get_action_type('update');
        $this->logger->save_log_action(array(
            'school_id' => $this->rmxSchool['id'],
            'campus_id' => $this->campusInfo['id'],
            'user_type' => $this->rmxUser['user_type'],
            'user_id' => $this->rmxUser['id'],
            'realname' => $this->rmxUser['realname'],
            'action_type' => $actionType,
            'content' => '重置定时开关机'
        ));

        exit(json("重置成功", true));
    }

    // 批量设置开关机时间页面
    public function power_time_batch_v2() {
        // 获取学校定时开关机时间
        $schoolPowerTime = $this->configModel->get_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->powerTimeV2Name);
        $schoolPowerTimeArr= $schoolPowerTime ? json_decode($schoolPowerTime['config_value'], true) : "";
        // 周日移到最后
        if(isset($schoolPowerTimeArr[1])) {
            $sundayPowerTimeArr = $schoolPowerTimeArr[1];
            unset($schoolPowerTimeArr[1]);
            $schoolPowerTimeArr[1] = $sundayPowerTimeArr;
        }
        $this->schoolPowerTimeArr = $schoolPowerTimeArr;

        $idStrBase64 = $this->get('idstr');
        $idStr = base64_decode($idStrBase64);
        $idArr = explode(',', $idStr);
        // 获取所有班牌
        $params['schoolId'] = $this->rmxSchool['id'];
        $params['campusId'] = $this->campusInfo['id'];
        $brandList = $this->classesModel->get_brand_list($params);
                    // echo '<pre>';var_export($brandList);exit;
        $brandList = array_value_to_key($brandList, 'id');
        $brandNameArr = array();
        foreach($idArr as $id) {
            if(isset($brandList[$id])) {
                array_push($brandNameArr, $brandList[$id]['class_name']);
            }
        }
        $this->brandIdJson = json_encode($idArr, JSON_UNESCAPED_UNICODE);
        $this->brandNameStr = implode('，', $brandNameArr);
        // var_export($this->brandIdJson);exit;
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "brand". DIRECTORY_SEPARATOR. "power_time_batch_v2");
    }

    // 批量设置定时开关机时间v2
    public function save_power_time_batch_v2(){
        $this->load->library('socket');
        $brandIdArr = $this->post("brand_arr");
        $week = $this->post("week");
        $postPowerTimeJson = $this->post("power_time_json");
        if(empty($brandIdArr)) {
            throw new Exception('参数错误');
        }
        $powerTime = $this->post("time") ? $this->post("time") : array();
        
        // var_export($powerTime);exit;
        $powerTimeJson = json_encode($powerTime);
        // 判断开机时间是否关机时间
        $arr = json_decode($powerTimeJson, true);
        $arrSort = array();
        foreach($arr as $time) {
            $startTime = $time['starttime'];
            $endTime = $time['endtime'];         
            $startTimeArr = explode(':', $startTime);
            $endTimeArr = explode(':', $endTime);
            if($startTimeArr[0] > $endTimeArr[0]){
                throw new Exception('开机时间不能大于关机时间');
            }
            if($startTimeArr[0] === $endTimeArr[0]){
                if($startTimeArr[1] === $endTimeArr[1]){
                    throw new Exception('开机时间不能等于关机时间');
                }
                if($startTimeArr[1] > $endTimeArr[1]){
                    throw new Exception('开机时间不能大于关机时间');
                }
            }
            // 按时间排序
            $arrSort[str_replace(':', '', $time['starttime'])] = array(
                'starttime' => $time['starttime'],
                'endtime' => $time['endtime']
            );
        }
        // 按时间排序
        ksort($arrSort);
        // 数组下标重0开始
        $arrSort = array_values($arrSort);
        // 判断开始时间是否大于上个结束时间
        foreach($arrSort as $key => $time) {
            // 从第二个开始判断
            if($key > 0) {
                $start = str_replace(':', '', $time['starttime']);
                $lastEnd = str_replace(':', '', $arrSort[$key - 1]['endtime']);
                if($start <= $lastEnd) {
                    throw new Exception('时间段不能重叠');
                }
            } 
        }
        $powerTimeArr = $arrSort;

        $schoolPowerTime = $this->configModel->get_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->powerTimeV2Name);
        $schoolPowerTimeArr= $schoolPowerTime ? json_decode($schoolPowerTime['config_value'], true) : "";

        // 判断是否有传时间，没有就使用学校默认时间
        if($postPowerTimeJson) {
            $batchPowerTimeArr = json_decode($postPowerTimeJson, true);
        } else {
            $batchPowerTimeArr = $schoolPowerTimeArr;
        }
        $batchPowerTimeArr[$week] = $powerTimeArr;
        $batchPowerTimeJson = json_encode($batchPowerTimeArr, JSON_UNESCAPED_UNICODE);
        // 计算定时开关机v2，返回给班牌
        $holiday = $this->configModel->get_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->powerHoliday);
        $powerTimeV2SocketData = $this->_get_power_time_v2($batchPowerTimeJson, $holiday['config_value']);

        // 批量设置
        $updateBatch = array();
        foreach($brandIdArr as $brandId) {
            $updateBatch[] = array(
                'id' => $brandId,
                'power_time_v2' => $batchPowerTimeJson,
                'updatetime' => date('Y-m-d H:i:s')
            );
        }
        if($updateBatch) {
            $this->db->update_batch(ClassesModel::$brandTable, $updateBatch, 'id');
        }

        // 推送消息到客户端
        $params['schoolId'] = $this->rmxSchool['id'];
        $params['campusId'] = $this->campusInfo['id'];
        $params['online'] = 1;
        $brandList = $this->classesModel->get_brand_list($params);
        $brandList = array_value_to_key($brandList, 'id');
        // echo '<pre>';var_export($brandList);exit;
        foreach($brandIdArr as $brandId) {
            if(isset($brandList[$brandId])) {
                $this->socket->send_power_time_v2_msg($brandId, $powerTimeV2SocketData);
            }
        }

        // 插入日志
        $this->load->library('logger');
        $actionType = $this->logger->get_action_type('update');
        $this->logger->save_log_action(array(
            'school_id' => $this->rmxSchool['id'],
            'campus_id' => $this->campusInfo['id'],
            'user_type' => $this->rmxUser['user_type'],
            'user_id' => $this->rmxUser['id'],
            'realname' => $this->rmxUser['realname'],
            'action_type' => $actionType,
            'content' => '批量设置定时开关机'
        ));

        // 返回开关机数据
        exit(json("保存成功", true, $batchPowerTimeJson));
    }

    // 获取设备版本
    public function get_version(){
        $brandId = $this->get("brand");
        $channelId = $this->get("channel");

        // 检查班牌状态
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo || !$brandInfo['is_online'] || $brandInfo['school_id'] != $this->rmxSchool['id']) throw new Exception("班牌已离线，获取设备版本失败");
        // 推送消息到客户端
        $this->load->library('socket');
        $this->socket->send_get_version_msg($brandId, $channelId);

        exit(json("", true));
    }

    // 更新设备版本
    public function update_version(){
        $brandId = $this->get("brand");
        $channelId = $this->get("channel");

        // 检查班牌状态
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo || !$brandInfo['is_online'] || $brandInfo['school_id'] != $this->rmxSchool['id']) throw new Exception("班牌已离线，发送版本更新请求失败");
        // 推送消息到客户端
        $this->load->library('socket');
        $this->socket->send_update_version_msg($brandId, $channelId);

        // 插入日志
        $this->load->library('logger');
        $actionType = $this->logger->get_action_type('brand');
        $this->logger->save_log_action(array(
            'school_id' => $this->rmxSchool['id'],
            'campus_id' => $this->campusInfo['id'],
            'user_type' => $this->rmxUser['user_type'],
            'user_id' => $this->rmxUser['id'],
            'realname' => $this->rmxUser['realname'],
            'action_type' => $actionType,
            'content' =>'更新设备版本，班牌id：' . $brandInfo['id']
        ));

        exit(json("发送版本更新请求成功", true));
    }

    // 获取本地考勤数据
    public function get_sign_data(){
        $brandId = $this->get("brand");
        $channelId = $this->get("channel");

        // 检查班牌状态
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        if(!$brandInfo || !$brandInfo['is_online'] || $brandInfo['school_id'] != $this->rmxSchool['id']) throw new Exception("班牌已离线，获取设备版本失败");
        // 推送消息到客户端
        $this->load->library('socket');
        $this->socket->send_get_sign_data_msg($brandId, $channelId);

        exit(json("", true));
    }

    // 保存缩放倍数
    public function save_brand_zoom_action(){
        $brandId = $this->post("id");
        $cameraZoom = $this->post("camera_zoom");

        // 判断教师权限
        $this->checkTeacherRoleByBrand($brandId);

        // 焦距最小值判断
        if($cameraZoom <= 0) throw new Exception("缩放比例不能小于0，请重新设置");

        // 检查是否设置全局配置
        if($brandId) {
            // 单独设置一块班牌
            $update['brand_camera_zoom'] = $cameraZoom;
            $this->db->update(ClassesModel::$brandTable, $update, "school_id='{$this->rmxSchool['id']}' AND `campus_id`='{$this->campusInfo['id']}' AND `id`='{$brandId}'");
        } else {
            // 设置全校班牌
            $this->configModel->save_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->cameraZoomName, $cameraZoom);
            // 更新全部校区班牌
            $update['brand_camera_zoom'] = $cameraZoom;
            $this->db->update(ClassesModel::$brandTable, $update, "school_id='{$this->rmxSchool['id']}' AND `campus_id`='{$this->campusInfo['id']}'");
        }
        exit(json("设置摄像头缩放比例成功", true));
    }

    // 保存考勤进入时间
    public function save_brand_sign_interval_action(){
        $brandId = $this->post("id");
        $signInterval = $this->post("sign-interval");

        // 判断教师权限
        $this->checkTeacherRoleByBrand($brandId);

        // 最小值判断
        if($signInterval < 0) throw new Exception("时间不能小于0，请重新设置");
        // if($signInterval > 100) throw new Exception(('时间不能大于100分钟'));

        // 检查是否设置全局配置
        if($brandId) {
            // 单独设置一块班牌
            $update['sign_interval'] = $signInterval;
            $this->db->update(ClassesModel::$brandTable, $update, "school_id='{$this->rmxSchool['id']}' AND `campus_id`='{$this->campusInfo['id']}' AND `id`='{$brandId}'");
        } else {
            // 设置全校班牌
            $this->configModel->save_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->signIntervalName, $signInterval);
            // 更新全部校区班牌
            $update['sign_interval'] = $signInterval;
            $this->db->update(ClassesModel::$brandTable, $update, "school_id='{$this->rmxSchool['id']}' AND `campus_id`='{$this->campusInfo['id']}'");
        }
        exit(json("设置考勤时间成功", true));
    }

    // 保存所属班级
    public function save_brand_class_action(){
        $brandId = $this->post("id");
        $classId = $this->post("class_id");
        // 判断教师权限
        $this->checkTeacherRoleByBrand($brandId);

        $this->db->update(ClassesModel::$brandTable, array('class_id' => $classId), "school_id='{$this->rmxSchool['id']}' AND `campus_id`='{$this->campusInfo['id']}' AND `id`='{$brandId}'");
        exit(json("修改所属班级成功", true));
    }

    // 班牌定时开关机管理页面，旧版已废弃
    public function power_time_old() {
        // 获取班牌定时开关机时间
        $schoolPowerTime = $this->configModel->get_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->powerTimeName);
        $this->powertime = $schoolPowerTime ? $schoolPowerTime['config_value'] : "";
        // 获取学校放假时间
        $holiday = $this->configModel->get_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->powerHoliday);
        if($holiday && isset($holiday['config_value'])) {
            $this->holidayArr = json_decode($holiday['config_value'], true);
        } else {
            $this->holidayArr = array();
        }
        // 获取每周定时失效时间
        $week = $this->configModel->get_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->powerWeek);
        if($week && isset($week['config_value'])) {
            $weekArr = explode(',', $week['config_value']);
            if(count($weekArr) === 7) {
                $weekStr = '整周';
            } else {
                $weekChineseArr = array_map(function($v) {
                    return transform_week_to_chinese($v);
                }, $weekArr);
                $weekStr = implode('&nbsp;&nbsp;&nbsp;&nbsp;', $weekChineseArr);
            }
            $this->weekStr = $weekStr;
        } else {
            // 如未设置，默认为整周
            $this->weekStr = '整周';
        }

        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "brand". DIRECTORY_SEPARATOR. "power_time");
    }
    // 获取放假时间
    public function get_power_holiday(){
        $holiday = $this->configModel->get_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->powerHoliday);
        if($holiday && isset($holiday['config_value'])) {
            $holidayArr = json_decode($holiday['config_value'], true);
        } else {
            $holidayArr = array();
        }

        exit(json("", true, $holidayArr));
    }
    // 保存学校放假时间
    public function save_power_holiday(){
        $holidayArr = $this->post("holiday") ? $this->post("holiday") : array();
        $holidayArrSort = array();
        foreach($holidayArr as $holiday) {
            // 验证日期是否合法
            if($holiday['startdate'] > $holiday['enddate']) {
                throw new Exception('开始日期不能大于结束日期');
            }
            if(isset($holidayArrSort[$holiday['startdate']])) {
                throw new Exception('放假时间不能重叠');
            }
            if(strtotime('+1 years', strtotime($holiday['startdate'])) < strtotime($holiday['enddate'])) {
                throw new Exception('放假时间不能超过一年');
            }
            $holidayArrSort[$holiday['startdate']] = array(
                'startdate' => $holiday['startdate'],
                'enddate' => $holiday['enddate']
            );
        }
        // 按开始时间排序
        sort($holidayArrSort);
        $holidayJson = json_encode($holidayArrSort, JSON_UNESCAPED_UNICODE);
        // 入库
        $this->configModel->save_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->powerHoliday, $holidayJson);
        // 推送消息到客户端
        $this->load->library('socket');
        $params['schoolId'] = $this->rmxSchool['id'];
        $params['campusId'] = $this->campusInfo['id'];
        $params['online'] = 1;
        $brandList = $this->classesModel->get_brand_list($params);
        // 班牌开关机时间（新逻辑）
        $week = $this->configModel->get_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], 'power_week');
        if($week && isset($week['config_value'])) {
            $weekArr = explode(',', $week['config_value']);
            sort($weekArr);
        } else {
            // 如未设置，默认为整周
            $weekArr = array(1,2,3,4,5,6,7);
        }
        foreach($brandList as $brand) {
            // 获取班牌开关机时间段
            $brandInfo = $this->classesModel->get_brand_info($brand['id']);
            // $powerTime = json_decode($brandInfo['power_time'], true);
            // $this->socket->send_power_time_msg($brand['id'], $powerTime, $weekArr, $holidayArrSort);


            // 计算定时开关机v2，返回给班牌
            $holiday = $this->configModel->get_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->powerHoliday);
            $powerTimeV2SocketData = $this->_get_power_time_v2($brand['power_time_v2'], $holidayJson);
            $this->socket->send_power_time_v2_msg($brandInfo['id'], $powerTimeV2SocketData);
        }

         // 插入日志
         $this->load->library('logger');
         $actionType = $this->logger->get_action_type('update');
         $this->logger->save_log_action(array(
             'school_id' => $this->rmxSchool['id'],
             'campus_id' => $this->campusInfo['id'],
             'user_type' => $this->rmxUser['user_type'],
             'user_id' => $this->rmxUser['id'],
             'realname' => $this->rmxUser['realname'],
             'action_type' => $actionType,
             'content' => '修改放假时间'
         ));

        exit(json("保存放假时间成功", true));
    }
    // 获取每周定时生效时间
    public function get_power_week(){
        $week = $this->configModel->get_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->powerWeek);
        if($week && isset($week['config_value'])) {
            $weekArr = explode(',', $week['config_value']);
        } else {
            // 如未设置，默认为整周
            $weekArr = array(1,2,3,4,5,6,7);
        }
        exit(json("", true, $weekArr));
    }
    // 保存每周定时生效时间
    public function save_power_week(){
        $weekArr = $this->post("weekArr") ? $this->post("weekArr") : array();
        if(empty($weekArr)) {
            throw new Exception('不能为空');
        }
        $week = implode(',', $weekArr);
        // 入库
        $this->configModel->save_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->powerWeek, $week);
        // 推送消息到客户端
        $this->load->library('socket');
        $params['schoolId'] = $this->rmxSchool['id'];
        $params['campusId'] = $this->campusInfo['id'];
        $params['online'] = 1;
        $brandList = $this->classesModel->get_brand_list($params);
        // 班牌开关机时间（新逻辑）
        $holiday = $this->configModel->get_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], 'power_holiday');
        if($holiday && isset($holiday['config_value'])) {
            $holidayArr = json_decode($holiday['config_value'], true);
        } else {
            $holidayArr = array();
        }
        foreach($brandList as $brand) {
            // 获取班牌开关机时间段
            $brandInfo = $this->classesModel->get_brand_info($brand['id']);
            $powerTime = json_decode($brandInfo['power_time'], true);
            $this->socket->send_power_time_msg($brand['id'], $powerTime, $weekArr, $holidayArr);
        }
        exit(json("保存成功", true));
    }

    // 设置年级开关机管理页面
    public function grade_power_time() {
        // 获取学校定时开关机时间
        $schoolPowerTime = $this->configModel->get_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->powerTimeV2Name);
        $this->powertime = $schoolPowerTime ? $schoolPowerTime['config_value'] : "";
        // 获取学校放假时间
        $holiday = $this->configModel->get_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->powerHoliday);
        if($holiday && isset($holiday['config_value'])) {
            $this->holidayArr = json_decode($holiday['config_value'], true);
        } else {
            $this->holidayArr = array();
        }
    
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "brand". DIRECTORY_SEPARATOR. "grade_power_time");
    }

    // 设置年级开关机管理页面
    public function get_grade_power_time_list() {
        // 获取学校定时开关机时间
        $schoolPowerTime = $this->configModel->get_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->powerTimeV2Name);
        $powertime = $schoolPowerTime ? $schoolPowerTime['config_value'] : "";
        $data['schoolId'] = $this->rmxSchool['id'];
        $data['campusId'] = $this->campusInfo['id'];
        $data['isDelete'] = 0;
        // $data['includeGraduated'] = 1;
        if($this->get('exclude_functional')) {
            // 是否排除功能课室
            $data['excludeFunctional'] = 1;
        }
        $gradeList = $this->classesModel->get_grade_list($data);
        
        // var_export($gradePowerTimeArr);exit;
        foreach($gradeList as $key => $grade) {
             // 获取年级定时开关机时间
            $gradePowerTime = $this->configModel->get_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->gradePowerTimeName . '_' . $grade['id']);
            $gradePowerTimeValue = $gradePowerTime ? $gradePowerTime['config_value'] : "";
            $arr = json_decode($gradePowerTimeValue, true);
            if(empty($arr)) {
                // 如未设置，为‘跟随系统’
                $gradeList[$key]['gradePowerTime'] = $powertime;  
            } else {
                $gradeList[$key]['gradePowerTime'] = $gradePowerTimeValue;   
            }
        }
        // echo'<pre>';var_export($gradeList);exit;

        // 返回值
        exit(admin_table_data(count($gradeList), $gradeList));

    }

    // 修改年级自定义时间页面
    public function grade_power_time_detail($gradeId) {
        // 获取学校定时开关机时间
        $schoolPowerTime = $this->configModel->get_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->powerTimeV2Name);
        $powertime = $schoolPowerTime ? $schoolPowerTime['config_value'] : "";
        $gradeInfo = $this->classesModel->get_grade_info($gradeId);
        // 获取年级定时开关机时间
        $gradePowerTime = $this->configModel->get_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->gradePowerTimeName . '_' . $gradeId);
        $gradePowerTimeValue = $gradePowerTime ? $gradePowerTime['config_value'] : "";
        $gradePowerTimeArr = array();
        if($gradePowerTimeValue) {
            $gradePowerTimeArr =  json_decode($gradePowerTimeValue, true);
        }
        if(empty($gradePowerTimeArr)) {
            // 如未设置，使用学校默认时间
            $gradePowerTimeArr =  json_decode($powertime, true);
        }
        // 周日移到最后
        if(isset($gradePowerTimeArr[1])) {
            $sundayPowerTimeArr = $gradePowerTimeArr[1];
            unset($gradePowerTimeArr[1]);
            $gradePowerTimeArr[1] = $sundayPowerTimeArr;
        }
        $this->gradeId = $gradeId;
        $this->gradeName = isset($gradeInfo['grade_name']) ? $gradeInfo['grade_name'] : '';
        $this->gradePowerTimeArr = $gradePowerTimeArr;
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "brand". DIRECTORY_SEPARATOR. "grade_power_time_detail");
    }

    // 获取年级定时开关机时间
    public function get_grade_power_time(){
        $gradeId = $this->get("grade_id");
        // 获取年级定时开关机时间
        $gradePowerTime = $this->configModel->get_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->gradePowerTimeName);
        $gradePowerTimeValue = $gradePowerTime ? $gradePowerTime['config_value'] : "";
        $arr = array();
        if($gradePowerTimeValue) {
            $gradePowerTimeArr = json_decode($gradePowerTimeValue, true);
            if($gradePowerTimeArr) {
                foreach($gradePowerTimeArr as $key => $value) {
                    if($key == $gradeId) {
                        $arr = $value;  
                    }
                }
            }
        }

        // echo'<pre>';var_export($arr);exit;
        exit(json("", true, $arr));
    }

    // 设置年级定时开关机时间（已废弃）
    public function save_grade_power_time_old(){
        $this->load->library('socket');
        $gradeId = $this->post("grade_id");
        if(empty($gradeId)) {
            throw new Exception('年级id不能为空');
        }

        $powerTime = $this->post("time") ? $this->post("time") : array();
        $powerTimeJson = json_encode($powerTime);
        // 判断开机时间是否关机时间
        $arr = json_decode($powerTimeJson, true);
        $arrSort = array();
        foreach($arr as $time) {
            $startTime = $time['starttime'];
            $endTime = $time['endtime'];         
            $startTimeArr = explode(':', $startTime);
            $endTimeArr = explode(':', $endTime);
            if($startTimeArr[0] > $endTimeArr[0]){
                throw new Exception('开机时间不能大于关机时间');
            }
            if($startTimeArr[0] === $endTimeArr[0]){
                if($startTimeArr[1] === $endTimeArr[1]){
                    throw new Exception('开机时间不能等于关机时间');
                }
                if($startTimeArr[1] > $endTimeArr[1]){
                    throw new Exception('开机时间不能大于关机时间');
                }
            }
            // 按时间排序
            $arrSort[str_replace(':', '', $time['starttime'])] = array(
                'starttime' => $time['starttime'],
                'endtime' => $time['endtime']
            );
        }
        // 按时间排序
        ksort($arrSort);
        // 数组下标重0开始
        $arrSort = array_values($arrSort);
        // 判断开始时间是否大于上个结束时间
        foreach($arrSort as $key => $time) {
            // 从第二个开始判断
            if($key > 0) {
                $start = str_replace(':', '', $time['starttime']);
                $lastEnd = str_replace(':', '', $arrSort[$key - 1]['endtime']);
                if($start <= $lastEnd) {
                    throw new Exception('时间段不能重叠');
                }
            } 
        }
        $powerTimeJson = json_encode($arrSort, JSON_UNESCAPED_UNICODE);

        // echo '<pre>';var_export($powerTimeJson);exit;

        // 班牌开关机时间（新逻辑）
        $week = $this->configModel->get_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], 'power_week');
        $holiday = $this->configModel->get_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], 'power_holiday');
        if($week && isset($week['config_value'])) {
            $weekArr = explode(',', $week['config_value']);
            sort($weekArr);
        } else {
            // 如未设置，默认为整周
            $weekArr = array(1,2,3,4,5,6,7);
        }
        if($holiday && isset($holiday['config_value'])) {
            $holidayArr = json_decode($holiday['config_value'], true);
        } else {
            $holidayArr = array();
        }

        $gradePowerTime = $this->configModel->get_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->gradePowerTimeName);
        // var_dump($gradePowerTime['config_value']);exit;
        if($gradePowerTime && $gradePowerTime['config_value']) {
            $gradePowerTimeValue = $gradePowerTime['config_value'];
            $gradePowerTimeArr = json_decode($gradePowerTimeValue, true);
            $exist = false;
            foreach($gradePowerTimeArr as $key => $value) {
                if($key == $gradeId) {
                    $gradePowerTimeArr[$key] = $arrSort;
                    $exist = true;
                }
            }
            // 该年级还没设置
            if($exist == false) {
                $gradePowerTimeArr[$gradeId] = $arrSort;
            }
            $gradePowerTimeJson = json_encode($gradePowerTimeArr, JSON_UNESCAPED_UNICODE);
        } else {
            $arr = array(
                $gradeId => $arrSort
            );
            $gradePowerTimeJson = json_encode($arr, JSON_UNESCAPED_UNICODE);
        }
        // echo '<pre>';var_export($gradePowerTimeJson);exit;
        // 设置年级班牌定时开关机时间
        $this->configModel->save_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->gradePowerTimeName, $gradePowerTimeJson);
        // 入库
        $classArr = $this->classesModel->get_class_list_by_grade($gradeId);
        // 班级id集合
        $classIdArr = array();
        $updateBatch = array();
        foreach($classArr as $class) {
            $updateBatch[] = array(
                'class_id' => $class['id'],
                'power_time' => $powerTimeJson,
                'updatetime' => date('Y-m-d H:i:s')
            );
            array_push($classIdArr, $class['id']);
        }
        if($updateBatch) {
            $this->db->update_batch(ClassesModel::$brandTable, $updateBatch, 'class_id');
        }

        if($classIdArr) {
            // 推送消息到客户端
            $classIdSet = implode(',', $classIdArr);
            $params['schoolId'] = $this->rmxSchool['id'];
            $params['campusId'] = $this->campusInfo['id'];
            $params['online'] = 1;
            $params['classIdSet'] = $classIdSet;
            $brandList = $this->classesModel->get_brand_list($params);
            // echo '<pre>';var_export($brandList);exit;
            foreach($brandList as $brand) {
                $this->socket->send_power_time_msg($brand['id'], $powerTimeJson, $weekArr, $holidayArr);
            }
        }

        exit(json("保存开关机时间成功", true));
    }

    // 设置年级定时开关机时间
    public function save_grade_power_time(){
        $this->load->library('socket');
        $gradeId = $this->post("grade");
        $week = $this->post("week");
        if(empty($gradeId)) {
            throw new Exception('年级id不能为空');
        }
        $powerTime = $this->post("time") ? $this->post("time") : array();
        $powerTimeJson = json_encode($powerTime);
        // 判断开机时间是否关机时间
        $arr = json_decode($powerTimeJson, true);
        $arrSort = array();
        foreach($arr as $time) {
            $startTime = $time['starttime'];
            $endTime = $time['endtime'];         
            $startTimeArr = explode(':', $startTime);
            $endTimeArr = explode(':', $endTime);
            if($startTimeArr[0] > $endTimeArr[0]){
                throw new Exception('开机时间不能大于关机时间');
            }
            if($startTimeArr[0] === $endTimeArr[0]){
                if($startTimeArr[1] === $endTimeArr[1]){
                    throw new Exception('开机时间不能等于关机时间');
                }
                if($startTimeArr[1] > $endTimeArr[1]){
                    throw new Exception('开机时间不能大于关机时间');
                }
            }
            // 按时间排序
            $arrSort[str_replace(':', '', $time['starttime'])] = array(
                'starttime' => $time['starttime'],
                'endtime' => $time['endtime']
            );
        }
        // 按时间排序
        ksort($arrSort);
        // 数组下标重0开始
        $arrSort = array_values($arrSort);
        // 判断开始时间是否大于上个结束时间
        foreach($arrSort as $key => $time) {
            // 从第二个开始判断
            if($key > 0) {
                $start = str_replace(':', '', $time['starttime']);
                $lastEnd = str_replace(':', '', $arrSort[$key - 1]['endtime']);
                if($start <= $lastEnd) {
                    throw new Exception('时间段不能重叠');
                }
            } 
        }
        $powerTimeArr = $arrSort;
        // var_dump($powerTimeArr);exit;
        // 获取年级定时开关机时间
        $gradePowerTime = $this->configModel->get_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->gradePowerTimeName . '_' . $gradeId);
        $gradePowerTimeValue = $gradePowerTime ? $gradePowerTime['config_value'] : "";
        $gradePowerTimeArr = json_decode($gradePowerTimeValue, true);
        if(empty($gradePowerTimeArr)) {
            // 如未设置，使用学校默认时间
            $schoolPowerTimeV2 = $this->configModel->get_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->powerTimeV2Name);
            $powertime = $schoolPowerTimeV2 ? $schoolPowerTimeV2['config_value'] : "";
            $gradePowerTimeArr = json_decode($powertime, true);
        }
        $gradePowerTimeArr[$week] = $powerTimeArr;
        $gradePowerTimeJson = json_encode($gradePowerTimeArr, JSON_UNESCAPED_UNICODE);
        // 计算定时开关机v2，返回给班牌
        $holiday = $this->configModel->get_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->powerHoliday);
        $powerTimeV2SocketData = $this->_get_power_time_v2($gradePowerTimeJson, $holiday['config_value']);

        // echo '<pre>';var_export($gradePowerTimeJson);exit;
        // 设置年级班牌定时开关机时间
        $this->configModel->save_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->gradePowerTimeName . '_' . $gradeId, $gradePowerTimeJson);
        // 入库
        $classArr = $this->classesModel->get_class_list_by_grade($gradeId);

        // 班级id集合
        $classIdArr = array();
        $updateBatch = array();
        foreach($classArr as $class) {
            $updateBatch[] = array(
                'class_id' => $class['id'],
                'power_time_v2' => $gradePowerTimeJson,
                'updatetime' => date('Y-m-d H:i:s')
            );
            array_push($classIdArr, $class['id']);
        }
        if($updateBatch) {
            $this->db->update_batch(ClassesModel::$brandTable, $updateBatch, 'class_id');
        }

        if($classIdArr) {
            // 推送消息到客户端
            $classIdSet = implode(',', $classIdArr);
            $params['schoolId'] = $this->rmxSchool['id'];
            $params['campusId'] = $this->campusInfo['id'];
            $params['online'] = 1;
            $params['classIdSet'] = $classIdSet;
            $brandList = $this->classesModel->get_brand_list($params);
            // echo '<pre>';var_export($brandList);exit;
            foreach($brandList as $brand) {
                $this->socket->send_power_time_v2_msg($brand['id'], $powerTimeV2SocketData);
            }
        }

        // 插入日志
        $this->load->library('logger');
        $actionType = $this->logger->get_action_type('update');
        $this->logger->save_log_action(array(
            'school_id' => $this->rmxSchool['id'],
            'campus_id' => $this->campusInfo['id'],
            'user_type' => $this->rmxUser['user_type'],
            'user_id' => $this->rmxUser['id'],
            'realname' => $this->rmxUser['realname'],
            'action_type' => $actionType,
            'content' => '修改年级定时开关机，年级id：' . $gradeId
        ));

        exit(json("保存成功", true));
    }

    // 获取周几的年级定时开关机时间v2
    public function get_grade_power_time_for_day() {
        $week = $this->get('week');
        $gradeId = $this->get('grade');
        $res = array();
        if($week) {
            // 获取年级定时开关机时间
            $gradePowerTime = $this->configModel->get_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->gradePowerTimeName . '_' . $gradeId);
            $gradePowerTimeValue = $gradePowerTime ? $gradePowerTime['config_value'] : "";
            $gradePowerTimeArr = json_decode($gradePowerTimeValue, true);
            if(empty($gradePowerTimeArr)) {
                // 如未设置，使用学校默认时间
                $schoolPowerTimeV2 = $this->configModel->get_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->powerTimeV2Name);
                $powertime = $schoolPowerTimeV2 ? $schoolPowerTimeV2['config_value'] : "";
                $gradePowerTimeArr = json_decode($powertime, true);
            }
            if($gradePowerTimeArr && isset($gradePowerTimeArr[$week]) && $gradePowerTimeArr[$week]) {
                $res = $gradePowerTimeArr[$week];
            }
        }
        exit(json('', true, $res));
    }

    // 班牌定时开关机管理页面
    public function power_time() {
        // 获取学校定时开关机时间v2
        $schoolPowerTimeV2 = $this->configModel->get_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->powerTimeV2Name);
        $this->powertime = $schoolPowerTimeV2 ? $schoolPowerTimeV2['config_value'] : "";
        $powerTimeArr =  json_decode($this->powertime, true);
        // 周日移到最后
        if(isset($powerTimeArr[1])) {
            $sundayPowerTimeArr = $powerTimeArr[1];
            unset($powerTimeArr[1]);
            $powerTimeArr[1] = $sundayPowerTimeArr;
        }
        // 如果是NULL，赋值array()
        if($powerTimeArr == NULL) {
            $powerTimeArr = array();
        }
        $this->powerTimeArr = $powerTimeArr;
        // var_export($powerTimeArr);exit;

        // 获取学校放假时间
        $holiday = $this->configModel->get_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->powerHoliday);
        if($holiday && isset($holiday['config_value'])) {
            $this->holidayArr = json_decode($holiday['config_value'], true);
        } else {
            $this->holidayArr = array();
        }

        // 获取年级
        $gradeParams['schoolId'] = $this->rmxSchool['id'];
        $gradeParams['campusId'] = $this->campusInfo['id'];
        $gradeParams['isDelete'] = 0;
        $this->gradeList = $this->classesModel->get_grade_list($gradeParams);
        // echo '<pre>';var_dump($this->powerTimeArr);exit;
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "brand". DIRECTORY_SEPARATOR. "power_time");
    }

    // 获取周几的定时开关机时间v2
    public function get_power_time_v2_for_day() {
        $week = $this->get('week');
        $brandId = $this->get('brand');
        $res = array();
        if($week) {
            if($brandId) {
                // 单个班牌
                $brandInfo = $this->classesModel->get_brand_info($brandId);
                $powertime = $brandInfo ? $brandInfo['power_time_v2'] : "";
                $powerTimeArr =  json_decode($powertime, true);
            } else {
                // 学校
                $schoolPowerTimeV2 = $this->configModel->get_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->powerTimeV2Name);
                $powertime = $schoolPowerTimeV2 ? $schoolPowerTimeV2['config_value'] : "";
                $powerTimeArr =  json_decode($powertime, true);
            }
            
            if($powerTimeArr && isset($powerTimeArr[$week]) && $powerTimeArr[$week]) {
                $res = $powerTimeArr[$week];
            }
        }
        exit(json('', true, $res));
    }

    // 某个班牌定时开关机管理页面
    public function brand_power_time($brandId) {
        // 获取班牌定时开关机时间v2
        $brandInfo = $this->classesModel->get_brand_info($brandId);
        $powerTimeArr = array();
        if($brandInfo['power_time_v2']) {
            $powerTimeV2 = $brandInfo['power_time_v2'];
            $powerTimeArr =  json_decode($powerTimeV2, true);
            // 周日移到最后
            if(isset($powerTimeArr[1])) {
                $sundayPowerTimeArr = $powerTimeArr[1];
                unset($powerTimeArr[1]);
                $powerTimeArr[1] = $sundayPowerTimeArr;
            }
        }
        if($brandInfo['class_id']) {
            $classInfo = $this->classesModel->get_class_info($brandInfo['class_id']);
        }

        $this->brandId = $brandId;
        $this->className = isset($classInfo['class_name']) ? $classInfo['class_name'] : '';
        $this->powerTimeArr = $powerTimeArr;
        // echo '<pre>';var_dump($this->powerTimeArr);exit;
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "brand". DIRECTORY_SEPARATOR. "brand_power_time");
    }

    // 推送班牌更新通知
    public function notify_brand_update() {
        $channelId = $this->post("channel");
        // 推送消息到客户端
        $params['schoolId'] = $this->rmxSchool['id'];
        $params['campusId'] = $this->campusInfo['id'];
        $params['online'] = 1;
        $brandList = $this->classesModel->get_brand_list_not_join($params);
        $this->load->library('socket');
        foreach($brandList as $brand) $this->socket->send_update_version_msg($brand['id'], $channelId);

        // 插入日志
        $this->load->library('logger');
        $actionType = $this->logger->get_action_type('brand');
        $this->logger->save_log_action(array(
            'school_id' => $this->rmxSchool['id'],
            'campus_id' => $this->campusInfo['id'],
            'user_type' => $this->rmxUser['user_type'],
            'user_id' => $this->rmxUser['id'],
            'realname' => $this->rmxUser['realname'],
            'action_type' => $actionType,
            'content' =>'批量更新设备版本'
        ));

        exit(json("发送版本更新请求成功", true));
    }

    // 批量重启班牌
    public function notify_brand_restart() {
        $channelId = $this->post("channel");
        // 推送消息到客户端
        $params['schoolId'] = $this->rmxSchool['id'];
        $params['campusId'] = $this->campusInfo['id'];
        $params['online'] = 1;
        $brandList = $this->classesModel->get_brand_list($params);
        $this->load->library('socket');
        foreach($brandList as $brand) $this->socket->send_power_restart_msg($brand['id'], $channelId);

        // 插入日志
        $this->load->library('logger');
        $actionType = $this->logger->get_action_type('brand');
        $this->logger->save_log_action(array(
            'school_id' => $this->rmxSchool['id'],
            'campus_id' => $this->campusInfo['id'],
            'user_type' => $this->rmxUser['user_type'],
            'user_id' => $this->rmxUser['id'],
            'realname' => $this->rmxUser['realname'],
            'action_type' => $actionType,
            'content' =>'批量重启班牌'
        ));

        exit(json("发送重启班牌请求成功", true));
    }

    // 设置班牌默认密码
    public function save_default_brand_paw(){
        $defaultBrandPaw = $this->post('default_brand_paw');
        // 入库
        $this->configModel->save_school_campus_config($this->rmxSchool['id'], $this->campusInfo['id'], $this->brandPawName, $defaultBrandPaw);
        // 更改该校区所有班牌密码
        $data = array(
            'brand_password' => $defaultBrandPaw,
            'updatetime' => date('Y-m-d H:i:s')
        );
        $this->db->update(ClassesModel::$brandTable, $data, "school_id='{$this->rmxSchool['id']}' AND `campus_id`='{$this->campusInfo['id']}'");

        exit(json("保存默认密码成功", true));
    }

    // 批量设置对话留言内容发送
    public function save_batch_allow_send(){
        $allowSend = $this->post('allow_send');
        // 更改该校区所有班牌密码
        $data = array(
            'allow_send' => $allowSend,
            'updatetime' => date('Y-m-d H:i:s')
        );
        $this->db->update(ClassesModel::$brandTable, $data, "school_id='{$this->rmxSchool['id']}' AND `campus_id`='{$this->campusInfo['id']}'");

        // 插入日志
        $this->load->library('logger');
        $actionType = $this->logger->get_action_type('brand');
        $this->logger->save_log_action(array(
            'school_id' => $this->rmxSchool['id'],
            'campus_id' => $this->campusInfo['id'],
            'user_type' => $this->rmxUser['user_type'],
            'user_id' => $this->rmxUser['id'],
            'realname' => $this->rmxUser['realname'],
            'action_type' => $actionType,
            'content' =>'批量设置对话留言内容发送'
        ));

        exit(json("批量设置成功", true));
    }

    // 外链管理页面
    public function custom_menu() {
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "brand". DIRECTORY_SEPARATOR. "custom_menu");
    }

    // 获取外链列表
    public function get_custom_menu_list() {
        // 获取数据条数
        $totalParams['schoolId'] = $this->rmxSchool['id'];
        $totalParams['getRowNumber'] = true;
        $total = $this->schoolModel->get_custom_menu_list($totalParams);
        // 获取数据
        $data['pageStart'] = $this->get('start');
        $data['pageSize']= $this->get("length");
        $data['schoolId'] = $this->rmxSchool['id'];
        $menuList = $this->schoolModel->get_custom_menu_list($data);
        foreach($menuList as &$menu) {
            // 显示位置
            $position = $menu['position'];
            $posiArr = explode(',', $position);
            $posiChineseArr = array();
            foreach($posiArr as $item) {
                if($item == CUSTOM_MENU_POSITION_BRAND) {
                    array_push($posiChineseArr, '电子班牌');
                } elseif($item == CUSTOM_MENU_POSITION_STUDENT) {
                    array_push($posiChineseArr, '学生移动端');
                } elseif($item == CUSTOM_MENU_POSITION_TEACHER) {
                    array_push($posiChineseArr, '教师移动端');
                }
            }
            $menu['position'] = implode('、', $posiChineseArr);
            // 显示方式
            $menu['mode'] = $menu['mode'] == CUSTOM_MENU_MODE_WEB ? '电脑端网页形式' : '手机端网页形式';
        }
         // 返回值
         exit(admin_table_data($total, $menuList));
    }

    // 编辑外链页面
    public function edit_custom_menu() {
        $id = $this->get('id');
        if($id) {
            // 获取外链详情
            $customMenu = $this->schoolModel->get_custom_menu_info($id);
            // 获取显示位置数组
            $customMenu['positionArr'] = explode(',', $customMenu['position']);
            $this->customMenu = $customMenu;
        }
        // 生成又拍云签名
        require_once('vendor/autoload.php');
        $serviceConfig = new Upyun\Config(UP_BUCKET, UP_USERNAME, UP_PASSWORD);
        $serviceConfig->setFormApiKey(UP_FORM_API);
        $serviceParams = $serviceConfig->getImageUploadParams(UP_FILEPATH, $this->policy, $this->signature);
        $this->display(ADMIN_DIR. DIRECTORY_SEPARATOR. "brand". DIRECTORY_SEPARATOR. "edit_custom_menu");
    }

    // 保存外链
    public function save_custom_menu_action() {
        $this->load->model('wxAppliModel');

        $id = $this->post('id');
        $icon = $this->post('img');
        $title = $this->post('title');
        $link = $this->post('link');
        $position = $this->post('position');
        $mode = $this->post('mode');
        // 内容检查
        if(empty($icon)) throw new Exception("请上传图标");
        if(empty($title)) throw new Exception("请填写标题");
        if(empty($link)) throw new Exception("请填写链接");
        if(empty($position)) throw new Exception("请选择位置");
        if(empty($mode)) throw new Exception("请选择方式");
        if(!strstr($link, 'http://') && !strstr($link, 'https://')) {
            throw new Exception("地址格式错误，不能缺少http://或https://");
        }
        // 入库
        $data['icon'] = $icon;
        $data['title'] = $title;
        $data['link'] = $link;
        $data['position'] = $position;
        $data['mode'] = $mode;
        $data['is_delete'] = 0;
        $data['updatetime'] = date("Y-m-d H:i:s");
        if($id) {
            $this->db->update(SchoolModel::$customMenuTable, $data, "id='{$id}'");
            $msg = '修改外链成功';
        } else {
            $data['school_id'] = $this->rmxSchool['id'];
            $data['createtime'] = $data['updatetime'];
            $this->db->insert(SchoolModel::$customMenuTable, $data);
            $id = $this->db->insert_id();
            $msg = '添加外链成功';
        }
        // 处理手机端菜单
        $positionArr = explode(',', $position);
        if(in_array(CUSTOM_MENU_POSITION_STUDENT, $positionArr)) {
            $studentAppli = $this->wxAppliModel->get_wx_application_by_custom_menu($id, BIND_TYPE_STUDENT);
            if(empty($studentAppli)) {
                // 插入学生移动端菜单
                $this->db->insert(WxAppliModel::$wxAppliTable, array(
                    'custom_menu_id' => $id,
                    'bind_user_type' => BIND_TYPE_STUDENT,
                    'createtime' => date("Y-m-d H:i:s"),
                    'updatetime' => date("Y-m-d H:i:s")
                ));
            }
        } else {
            // 删除对应的学生已添加菜单
            $appliList = $this->wxAppliModel->get_wx_application_list(array(
                'isDelete' => 0,
                'customMenuId' => $id,
                'bindUserType' => BIND_TYPE_STUDENT
            ));
            if($appliList) {
                // 删除对应用户添加的菜单记录
                foreach($appliList as $appli) {
                    $appliId = $appli['id'];
                    // 获取用户添加的菜单
                    $userAppliList = $this->wxAppliModel->get_wx_user_appli_list(array(
                        'isDelete' => 0,
                        'appliId' => $appliId
                    ));
                    foreach($userAppliList as $userAppli) {
                        $appliIdArr = explode(',', $userAppli['appli_ids']);
                        foreach($appliIdArr as $key => $item) {
                            if($item == $appliId) {
                                unset($appliIdArr[$key]);
                            }
                        }
                        $this->db->update(WxAppliModel::$wxUserAppliTable, array(
                            'appli_ids' => implode(',', $appliIdArr),
                            'updatetime' => date("Y-m-d H:i:s")
                        ), array(
                            'id' => $userAppli['id']
                        ));
                    }
                }
            }
            // 删除对应的学生移动端菜单
            $this->db->update(WxAppliModel::$wxAppliTable, array(
                'is_delete' => 1,
                'updatetime' => date("Y-m-d H:i:s")
            ), array(
                'custom_menu_id' => $id,
                'bind_user_type' => BIND_TYPE_STUDENT
            ));
        }
        if(in_array(CUSTOM_MENU_POSITION_TEACHER, $positionArr)) {
            // 插入教师移动端菜单
            $teacherAppli = $this->wxAppliModel->get_wx_application_by_custom_menu($id, BIND_TYPE_TEACHER);
            if(empty($teacherAppli)) {
                // 插入教师移动端菜单
                $this->db->insert(WxAppliModel::$wxAppliTable, array(
                    'custom_menu_id' => $id,
                    'bind_user_type' => BIND_TYPE_TEACHER,
                    'createtime' => date("Y-m-d H:i:s"),
                    'updatetime' => date("Y-m-d H:i:s")
                ));
            }
        } else {
            // 删除已添加的菜单
            $appliList = $this->wxAppliModel->get_wx_application_list(array(
                'isDelete' => 0,
                'customMenuId' => $id,
                'bindUserType' => BIND_TYPE_TEACHER
            ));
            // var_export($appliList);exit;
            if($appliList) {
                // 删除对应用户添加的菜单记录
                foreach($appliList as $appli) {
                    $appliId = $appli['id'];
                    // 获取用户添加的菜单
                    $userAppliList = $this->wxAppliModel->get_wx_user_appli_list(array(
                        'isDelete' => 0,
                        'appliId' => $appliId
                    ));
                    // var_export($userAppliList);exit;
                    foreach($userAppliList as $userAppli) {
                        $appliIdArr = explode(',', $userAppli['appli_ids']);
                        foreach($appliIdArr as $key => $item) {
                            if($item == $appliId) {
                                unset($appliIdArr[$key]);
                            }
                        }
                        $this->db->update(WxAppliModel::$wxUserAppliTable, array(
                            'appli_ids' => implode(',', $appliIdArr),
                            'updatetime' => date("Y-m-d H:i:s")
                        ), array(
                            'id' => $userAppli['id']
                        ));
                    }
                }
            }
            // 删除对应的教师移动端菜单
            $this->db->update(WxAppliModel::$wxAppliTable, array(
                'is_delete' => 1,
                'updatetime' => date("Y-m-d H:i:s")
            ), array(
                'custom_menu_id' => $id,
                'bind_user_type' => BIND_TYPE_TEACHER
            ));
        }
        exit(json($msg, true));
    }

    // 删除外链
    public function delete_custom_menu_action() {
        $this->load->model('wxAppliModel');
        $menuId = $this->post("id");
        // 处理手机端菜单
        $appliList = $this->wxAppliModel->get_wx_application_list(array(
            'isDelete' => 0,
            'customMenuId' => $menuId
        ));
        if($appliList) {
            // 删除对应用户添加的菜单记录
            foreach($appliList as $appli) {
                $appliId = $appli['id'];
                // var_export($appliId);exit;
                // 获取用户添加的菜单
                $userAppliList = $this->wxAppliModel->get_wx_user_appli_list(array(
                    'isDelete' => 0,
                    'appliId' => $appliId
                ));
                foreach($userAppliList as $userAppli) {
                    $appliIdArr = explode(',', $userAppli['appli_ids']);
                    foreach($appliIdArr as $key => $item) {
                        if($item == $appliId) {
                            unset($appliIdArr[$key]);
                        }
                    }
                    $this->db->update(WxAppliModel::$wxUserAppliTable, array(
                        'appli_ids' => implode(',', $appliIdArr),
                        'updatetime' => date("Y-m-d H:i:s")
                    ), array(
                        'id' => $userAppli['id']
                    ));
                }
            }
        }
        // 删除对应的手机端菜单
        $this->db->update(WxAppliModel::$wxAppliTable, array(
            'is_delete' => 1,
            'updatetime' => date("Y-m-d H:i:s")
        ), array(
            'custom_menu_id' => $menuId
        ));

        // 执行删除操作
        $save['is_delete'] = 1;
        $this->db->update(SchoolModel::$customMenuTable, $save, "id='{$menuId}'");
        exit(json("删除成功", true));
    }

    // 导出班牌对应班级
    public function export_brand_class() {
        // 获取数据
        $data['schoolId'] = $this->rmxSchool['id'];
        $data['campusId'] = $this->campusInfo['id'];
        $data['orderByClassName'] = 1;
        $brandList = $this->classesModel->get_brand_list_left_join_class($data);
        $exportData = array();
        // echo '<pre>';var_export($studentList);exit;
        $firstRow = array(
            '班牌id',
            '所属班级'
        );
        $exportData[] = $firstRow;
        // 获取全校班级
        $classParams['isDelete'] = 0;
        $classParams['schoolId'] = $this->rmxSchool['id'];
        $classParams['campusId'] = $this->campusInfo['id'];
        $classList = $this->classesModel->get_class_list($classParams);
        $classList = array_value_to_key($classList, 'id');
        // 获取学生其他信息
        foreach($brandList as &$brand) {
            $brand['className'] = isset($classList[$brand['class_id']]) ? $classList[$brand['class_id']]['class_name'] : '';
            $arr = array(
                $brand['id'],
                $brand['className'],
            );
            $exportData[] = $arr;
        }
        $widthParams = array(
            array(
                'index' => 'B',
                'width' => 16
            ),
            array(
                'index' => 'C',
                'width' => 20
            )
        );
        exportExcel($this->rmxSchool['school_name'] . '班牌id对应关系表', $exportData, $widthParams);
    }
}